package com.zl.auth.client.utils;

import com.alibaba.fastjson.JSON;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.RequestEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import sun.jvm.hotspot.memory.HeapBlock;

import javax.servlet.http.Cookie;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpClientUtil {
    /**
     * 只能发送表单格式参数
     * get请求发送Json格式的参数有问题，建议使用post发送json格式数据
     * @param url
     * @param params
     */
    public static void sendGet(String url, Map<String,Object> params){

        try {
            CloseableHttpClient client = HttpClients.createDefault();
            url = url.concat("?");
            //Url编码
            for (Map.Entry<String,Object> e : params.entrySet()) {
                url = url.concat(e.getKey()).concat("=").concat(URLEncoder.encode(String.valueOf(e.getValue()), "UTF-8")).concat("&");
            }
            url = url.substring(0,url.length()-1);
            HttpGet get = new HttpGet(url);
            //设置为form表单格式参数
            get.setHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            //设置cookie
            get.setHeader("Cookie","platFormU2Token=4B4AF45659F5B41AA1D0A38279AB15BE;platFormTeacherEmail=testdemo2@xdf.cn;JSESSIONID=86774010B969A39645B608E51BA2BB70");
            CloseableHttpResponse response = client.execute(get);
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                String bodyAsString = EntityUtils.toString(response.getEntity(),"UTF-8");
                System.out.println(bodyAsString);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 只能发送json格式参数，需扩展
     * @param url
     * @param params
     */
    public static void sendPostJson(String url, Map<String,Object> params, List<Header> headers, Cookie[] cookies) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300 * 1000)
                    .setConnectTimeout(300 * 1000)
                    .build();
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            //设置json格式参数传递
            if (headers == null){
                headers = new ArrayList<>();
            }
            headers.add(new BasicHeader("Content-Type","application/json;charset=utf-8"));
            //设置cookie信息
            StringBuilder cookieStr = new StringBuilder();
            if (cookies != null && cookies.length > 0){
                for (int i = 0; i < cookies.length; i++) {
                    Cookie c = cookies[i];
                    cookieStr.append(c.getName()).append("=").append(c.getValue()).append(";");
                }
            }
            if (cookieStr.length() > 0){
                headers.add(new BasicHeader("Cookie",cookieStr.substring(0,cookieStr.length()-1)));
            }
//            post.setHeader("Cookie","token=4B4AF45659F5B41AA1D0A38279AB15BE;JSESSIONID=86774010B969A39645B608E51BA2BB70");
            post.setHeaders(headers.toArray(new Header[headers.size()]));
            String requestParams = JSON.toJSONString(params);
            StringEntity postingString = new StringEntity(requestParams,
                    "utf-8");
            post.setEntity(postingString);
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());
            System.out.println(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String sendPostForm(String url, Map<String,Object> params, List<Header> headers, Cookie[] cookies) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300 * 1000)
                    .setConnectTimeout(300 * 1000)
                    .build();
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            if (headers == null){
                headers = new ArrayList<>();
            }
            headers.add(new BasicHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"));
            //设置cookie信息
            StringBuilder cookieStr = new StringBuilder();
            if (cookies != null && cookies.length > 0){
                for (int i = 0; i < cookies.length; i++) {
                    Cookie c = cookies[i];
                    cookieStr.append(c.getName()).append("=").append(c.getValue()).append(";");
                }
            }
            if (cookieStr.length() > 0){
                headers.add(new BasicHeader("Cookie",cookieStr.substring(0,cookieStr.length()-1)));
            }
            post.setHeaders(headers.toArray(new Header[headers.size()]));
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            if (params != null && params.size() > 0){
                Set<Map.Entry<String,Object>> set = params.entrySet();
                for (Map.Entry<String,Object> entry : set) {
                    NameValuePair n = new BasicNameValuePair(entry.getKey(),String.valueOf(entry.getValue()));
                    list.add(n);
                }
            }
            StringEntity entity = new UrlEncodedFormEntity(list, HTTP.UTF_8);
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());
            return content;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
